import { createRouter, createWebHistory } from 'vue-router';
import config from "@/config";
import store from '@/store';
import { message } from 'ant-design-vue';

const routes = config.routes;

function generatePath(page) {
    let obj = routes[page];
    let result = {
        path: '/' + page,
        name: page,
        meta: { layout: "pc", showAs: obj.showAs || page },
        component: null
    };
    if (typeof obj === "function") {
        result.component = obj;
    } else {
        if (obj.layout) {
            obj.meta = { layout: obj.layout, showAs: obj.showAs || page };
        }
        result = { ...result, ...obj };
    }
    return result;
}

let pages = [];
for (let pc in routes) {
    pages.push(generatePath(pc));
}

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes: pages
});



function pageJmp(to, next) {
    document.title = to.meta.title;
    store.dispatch({ type: 'setSelectedKeys', selectedKeys: [to.meta.subMenuKey] });
    store.dispatch({ type: 'setOpenKeys', openKeys: [to.meta.menuKey] });
    next();
}

function fallbackJmp(next) {
    var fallbackName = "";
    var fallbackItem = null;
    if (config.authFallback) {
        fallbackName = config.authFallback;
        var filter = pages.filter((item) => item.name == fallbackName);
        if (filter.length > 0) {
            fallbackItem = filter[0];
        }
    }
    if (!fallbackItem) {
        var filter = pages.filter((item) => item.meta.requireAuth == false);
        if (filter.length > 0) {
            fallbackItem = filter[0];
        }
    }
    console.log(fallbackItem)
    document.title = fallbackItem.meta.title;
    store.dispatch({ type: 'setSelectedKeys', selectedKeys: [fallbackItem.meta.subMenuKey] });
    store.dispatch({ type: 'setOpenKeys', openKeys: [fallbackItem.meta.menuKey] });
    next(fallbackItem.path);
}

/**
 * 1. Check authentication
 * 2. Change page title
 * 3. Update menu and submenu keys
 */
router.beforeEach(async (to, from, next) => {
    try {
        if (to.meta.requireAuth && config.sessionAction && typeof config.sessionAction === 'function') {
            const res = await config.sessionAction();
            
            if (!res.login) {
                message.warning('请先登录系统');
                fallbackJmp(next);
                return;
            }
            
            // 检查路由权限
            if (to.meta.permission) {
                // 导入权限检查函数
                const { checkPermission } = await import('@/utils/permission');
                
                // 检查用户是否有权限访问该路由
                if (!checkPermission(to.meta.permission)) {
                    message.warning('您没有权限访问该页面');
                    next(from.path || '/');
                    return;
                }
            }
            
            pageJmp(to, next);
        } else {
            pageJmp(to, next);
        }
    } catch (error) {
        console.error('Session检查失败:', error);
        message.error('登录状态验证失败');
        fallbackJmp(next);
    }
});

export default router;
